
var battery;

var _phraseContainer;
var _phraseTextarea;
var _phraseButtons;

var _devMessage;

function onSendDevMessage()
{
	_devMessage = $( '#dev_message_container' ).clone();

	_devMessage.attr( 'id', "dev_message_container_active" );

	fancybox(	_devMessage,
				{
					padding: "0px",
					beforeShow: function()
					{
						$(".fancybox-skin").css("backgroundColor","rgb(195,195,195)");
					},
					afterShow: function()
					{
						_devMessage.find( 'textarea' ).focus();
					}
				}
	);
}

function sendDevMessage()
{
	var message = _devMessage.find( 'textarea' ).val();

	var sendDevMessageButtons = _devMessage.find( '.phrase-blue-button' );

	ajax(	{
				'url': "/send-dev-message/",
				'dataType': "json",
				'data':
				{
					'message': message,
				},
				'success':
					function()
					{
						$( sendDevMessageButtons[ 0 ] ).text( "Отправлено..." );
						sendDevMessageButtons.removeClass( 'phrase-blue-button' );
						sendDevMessageButtons.addClass( 'phrase-blue-button-inactive' );

						setTimeout(
							function()
							{
								closeFancybox();
							},
							1000
						);
					}
			}
	);
}

var randomPhrase =
{
	_timeout: 15000,
	_animateInt: 1000,
	_maxPhraseLen: 100,

	setNextData: function( userId, phrase )
	{
		this._nextData = {};
		this._nextData.userId = userId;
		this._nextData.phrase = phrase;
	},

	_startUpdate: function()
	{
		// It's a loop to update phrase info

		var obj = $( '.random-phrase:first' );
		var this_ = this;

		var width = obj.width();

		obj.animate( 
			{
				right: "-" + String( width ) + "px"
			},
			this._animateInt,
			function()
			{
				obj.find( '[name=image]' ).attr( 'src', this_._smallPhotoUrl );
				obj.find( '[name=user_name]' ).html( format( "<a href='{0}' target='_blank'>{1}</a>", this_._anketaLink, this_._name ) );
				obj.find( '[name=phrase]' ).text( trunkStr( this_._phrase, this_._maxPhraseLen, '...' ) );
				
				obj.css( 'visibility', "visible" );
				obj.animate( { right: "0px" }, this._animateInt );


				var spanAddToMy = obj.find( '.add-to-my-phrases > span' );
				spanAddToMy.text( "Добавить в мои фразы" );
				spanAddToMy.css( 'cursor', "pointer" );
				spanAddToMy.css( 'border-bottom', "1px dashed" );
				spanAddToMy.on( 'click',
									function()
									{
										spanAddToMy.text( "Фраза добавлена" );
										spanAddToMy.css( 'cursor', "default" );
										spanAddToMy.css( 'border-bottom', "0px" );
										spanAddToMy.off( 'click' );

										ajax(
											{
												url: '/add-to-my-phrases/',
												data:
												{
													'phrase': this_._phrase,
													'look_for': LOOK_FOR
												},
											}
										);
									}																																			
				);
			}
		);
	},

	_ancetInfo: function()
	{
		this_ = this;

		mamba.api(
			{
				'method': "anketa.getInfo",
				'oids': this._userId
			},
			function( err, data_ )
			{
				var data = data_[ 'data' ][ 0 ];
								
				this_._smallPhotoUrl = data[ 'info' ][ 'small_photo_url' ];
				this_._name = data[ 'info' ][ 'name' ];
				this_._anketaLink = data[ 'info' ][ 'anketa_link' ];
	
				this_._startUpdate();
			}
		);
	},


	loop: function()
	{
		var this_ = this;

		if( this._nextData != null )
		{
			this_._phrase = this._nextData.phrase;
			this_._userId = this._nextData.userId;			

			this._ancetInfo();
		}
		else
		{
			ajax( 
				{
					'url': '/get-user-random-phrase/',
					'dataType': "json",
					'success':
						function( data )
						{
							this_._phrase = data[ 'phrase' ];
							this_._userId = data[ 'user_id' ];	
	
							this_._ancetInfo();
						}
				}		
			);
		}

		this._nextData = null;

		setTimeout( function() { this_.loop(); }, this_._timeout );
	}
};

function onAddMyPhrase()
{	
	var _phraseContainer = $( '#add_my_phrase_container' ).clone();
	_phraseContainer.attr( 'id', "add_my_phrase_container_active" );

	_phraseButtons = _phraseContainer.find( '.phrase-blue-button' );

	_phraseTextarea = _phraseContainer.find( 'textarea' );
	fancybox(	_phraseContainer,
				{
					padding: "0px",
					beforeShow: function()
					{
						$(".fancybox-skin").css("backgroundColor","rgb(195,195,195)");
					},
					afterShow: function()
					{
						_phraseTextarea.focus();
					}
				}
	);
}

function onSaveMyPhrase()
{
	var phrase = _phraseTextarea.val();
	ajax(	{
				'url': "/save-my-phrase/",		
				'data':
				{
					'look_for': LOOK_FOR,
					'phrase': phrase
				},
				'dataType': "json",
				'success':
					function()
					{
						$( _phraseButtons[ 0 ] ).text( "Сохранено..." );
						_phraseButtons.removeClass( 'phrase-blue-button' );
						_phraseButtons.addClass( 'phrase-blue-button-inactive' );

						setTimeout(
							function()
							{
								$.fancybox.close();
							},
							1000
						);

						// show phrase in randomPhrase window
						randomPhrase.setNextData( userId, phrase );
					}
			}
	);
}

function onCancelMyPhrase()
{
	$.fancybox.close();
}

function onLoadSection()
{
	setTitle( 'Поиск идеала...' );
	
	
	$.fancybox.hideLoading();

	mamba.init(
		function()
		{
			//console.info( "OK" );
		},
		function()
		{
			console.info( "BAD" );
		}
	);

	randomPhrase.loop(); // start showing random phrases
	
	update();
}

function onShowPay()
{
	fancybox(	$( '#pay_form_container' ).html(), 
				{ 
					beforeShow: function()
					{
						$(".fancybox-skin").css("backgroundColor","rgb(40,40,40)");
					} 
				} 
	);

	clearDetectIfPayed();
	detectIfPayed.interval = setInterval( detectIfPayed, 15000 ); // check every 15 seconds if the cur. user payed
}

function clearDetectIfPayed()
{	
	if( detectIfPayed.interval != null )
	{	
		detectIfPayed.time = 0;
		clearInterval( detectIfPayed.interval );
	}
}

function detectIfPayed()
{
	if( detectIfPayed.time < 20 ) // check for 20*15 = 300 seconds if the cur. user payed
	{
		detectIfPayed.time++;
	}
	else
	{
		// reset
		clearDetectIfPayed();
	}
}

detectIfPayed.time = 0;
detectIfPayed.inteval = null;

function onMoveMeToAdvBlock()
{
	fancybox( $( '#on_move_me_to_adv_block_message' ).html() );
}

function onPay( userId )
{	
	$.fancybox.close();
	mamba.method( 'pay', 1, format( 'from_id_{0}', userId ) );
	fancybox( $( '#wait_after_pay_message' ).html() );
}

function goToSearch()
{
	$.fancybox.showLoading();
	loader.load( 3, { next_section: 4 } );	
}

function closeFancybox()
{
	$.fancybox.close();
}

function closeFancyboxGoToContacts()
{
	$.fancybox.close();
	goToContacts();
}

function goToContacts()
{
	$.fancybox.showLoading();
	loader.load( 2, { next_section: 4 } );	
}

// main info

var MAX_NUM_PHOTOS = 11; // maximum number of small photos

function fancybox( html, props_ )
{
	var props = { 
					autoSize: true,
					helpers: 
					{
						overlay: 
						{
							locked: false
						}
					}  
	};	

	if( props_ != undefined )
	{
		for( var i in props_ )
		{
			props[ i ] = props_[ i ];
		}
	}

	$.fancybox( html, props );
}

function closeMessage()
{
	$.fancybox.close();	
}

// choose a rangom phrase
var _messageContainer;

var curPhraseType;

var addToMyPhrases = 
{
	_name: 'add_to_my_phrases_container',
	_obj: null,

	_remove: function()
	{
		if( this._obj != null )
		{
			this._obj.remove();
			this._obj = null;
		}
	},

	reset: function( curPhrase, parent )
	{
	    this._remove();
		
		if( this._obj == null )
		{
			this._append( parent );
		}

		this._curPhrase = curPhrase;
		this._setText( 'Добавить в мои фразы' );
		this._setBkImg( '/static/img/blue-arrow.png' );

		var clickSpan = this._obj.find( 'span' );
		clickSpan.attr( 'class', 'blue-link' );
		var this_ = this;
		clickSpan.on( 'click', function() { this_._onAdd(); } );
	},

	_append: function( parent )
	{
		this._obj = $( '[name=' + this._name + ']' ).clone();

		this._obj.css( 'display', "block" );

		var html = this._obj.html();
		var parentHtml = parent.html();

		parent.append( this._obj );
	},

	_onAdd: function()
	{
		var this_ = this;

		ajax(
			{
				url: '/add-to-my-phrases/',
				data:
				{
					'phrase': this._curPhrase,
					'look_for': LOOK_FOR
				},
				success:
					function()
					{
						this_._phraseAdded();
					}
			}
		);		
	},

	_setText: function( text )
	{
		this._obj.find( 'span' ).text( text );
	},

	_setBkImg: function( img )
	{
		this._obj.find( '.add-to-my-phrases-image' ).css( 'background-image', format( "url({0})", img ) );
	},

	_phraseAdded: function()
	{
		this._setText( 'Фраза добавлена' );
		this._setBkImg( '/static/img/check.png' );

		this._obj.find( 'span' ).attr( 'class', '' );

		var clickSpan = this._obj.find( 'span' );
		clickSpan.off( 'click' );
	}
};

function choosePhrase( type )
{
	curPhraseType = type;
	
	ajax(
		{
			'url' : '/get-dating-phrase/',
			'data': 
			{
				'companion_sex': LOOK_FOR == 'M' ? 'm': 'f',
				'my_name': MY_NAME,
				'companion_name': "Tatiana",
				'type': type
			},
			'dataType': "json",
			'success':
				function( data )
				{
					var canShowPhrase = ( data[ 'phrase' ] != "null" ? true : false );

					var textareaId = 'message_active';

					function showActions( bShow )
					{
						var ids = [ 'other_phrase_active', 'phrase_screen_back_active' ];
						if( bShow )
						{
							for( var i = 0; i < ids.length; i++ )
							{
								$( '#' + ids[ i ] ).show();
							}
						}
						else
						{
							for( var i = 0; i < ids.length; i++ )
							{
								$( '#' + ids[ i ] ).hide();
							}							
						}
					}

					if( canShowPhrase )
					{
						var phrase = data[ 'phrase' ];

						var textarea = $( '#' + textareaId );

						textarea.text( phrase );
	
						$( '#send_message_hint1_active' ).hide();
						$( '#send_message_hint2_active' ).show();
	
						$( '#choose_words_link1_active' ).text( "Другие слова" );
	
						$( '#copy_to_clipboard_container_active' ).show();
						$( '#copy_to_clipboard_active' ).attr( 'data-clipboard-text', phrase );
	
						_initClipboard( 'copy_to_clipboard_active' );

						showActions( true );
						
						if( type != 'my' ) // if not 'my' phrases
						{
							addToMyPhrases.reset( phrase, textarea );
						}
					}
					else
					{

						if( type != 'my' )
						{
							$( '#' + textareaId ).html( $( '#pay_for_phrase' ).html() );							
						}
						else
						{
							$( '#' + textareaId ).html( $( '#you_have_not_saved_phrases' ).html() );							
						}

						showActions( true );
					}
				}
		}
	);
}

var _messageInfo = 
{
	name: "",
	photoSrc: ""
};

function _initClipboard( id )
{
	var clip = new ZeroClipboard(
		$( '#' + id ), 
		{
			moviePath: "ZeroClipboard/ZeroClipboard.swf"
		}
	);
}



function onPhraseScreenBack()
{
	var node = $( '#send_message_container' ).clone();
	_changeMessageContainerIds( node );
	$( '#send_message_container_active' ).html( node.html() );
	_messageAddUserData();
}

function _changeMessageContainerIds( node )
{
	node.find( '[id=message]' ).attr( 'id', 'message_active' );
	node.find( '[id=message_photo]' ).attr( 'id', 'message_photo_active' );
	node.find( '[id=message_name]' ).attr( 'id', 'message_name_active' );

	node.find( '[id=send_message_hint1]' ).attr( 'id', 'send_message_hint1_active' );
	node.find( '[id=send_message_hint2]' ).attr( 'id', 'send_message_hint2_active' );

	node.find( '[id=choose_words_link1]' ).attr( 'id', 'choose_words_link1_active' );
	node.find( '[id=copy_to_clipboard]' ).attr( 'id', 'copy_to_clipboard_active' );
	node.find( '[id=copy_to_clipboard_container]' ).attr( 'id', 'copy_to_clipboard_container_active' );

	node.find( '[id=ancet_link]' ).attr( 'id', 'ancet_link_active' );
	node.find( '[id=other_phrase]' ).attr( 'id', 'other_phrase_active' );
	node.find( '[id=phrase_screen_back]' ).attr( 'id', 'phrase_screen_back_active' );
}

function _messageAddUserData()
{
	$( '#message_active' ).focus();
	$( '#message_name_active' ).text( _messageInfo.name );
	$( '#ancet_link_active' ).attr( 'href', _messageInfo.ancetUrl );
	$( '#message_photo_active' ).attr( 'src',  _messageInfo.photoSrc );
}

function onSendMessage()
{
	var node = $( '#send_message_container' ).clone();
	node.attr( 'id', 'send_message_container_active' );

	_changeMessageContainerIds( node );

	fancybox( node,	{
						padding: "0px",
						beforeShow: function()
						{
							$(".fancybox-skin").css("backgroundColor","rgb(195,195,195)");
						},
						afterShow: function()
						{
							_messageAddUserData();
						},
						afterClose: function()
						{
							node.remove();
						}
					}
	);

	var clip = new ZeroClipboard($("#d_clip_button"), {
      moviePath: "/static/ZeroClipboard/ZeroClipboard.swf"
    });
}

function onPhotos()
{
	var sel = "#fancy0";
	
	var found = ( $( sel ).length == 0 ) ? false: true;
	
	if( found )
	{
		$( sel ).trigger( "click" );
	}
	else
	{
		fancybox( "<table height='100%'><tr><td valign='middle'><b>Фотографии не найдены.</b></td></tr></table>" );
	}
}

function getAgeNotation( age )
{
	var div = age % 10;
	if( div == 1 )
	{
		return "год";
	}
	else
	if( div > 1 && div < 5 )
	{
		return "года";
	}
	else
	{
		return "лет";
	}
}

var _notShowedUsers = []; // cached users (extra users to show without ajax request)

var _isPayedMode = false;

var updateMode =
{
	isUpdate: false,
	
	set: function( isUpdate )
	{
		this.isUpdate = isUpdate;
		
		if( isUpdate )
		{
			$( '#ancet-loader' ).css( 'visibility', "visible" );
			$( '[name=next]' ).attr( 'class', "gray-arrow-disabled" );
			$( '[name=next]' ).removeAttr( 'onclick' );
			$( '[name=next]' ).removeAttr( 'title' );					
		}
		else
		{
			$( '#ancet-loader' ).css( 'visibility', "hidden" );
			$( '[name=next]' ).attr( 'class', "gray-arrow" );
			$( '[name=next]' ).attr( 'onclick', "update()" );
			$( '[name=next]' ).attr( 'title', "Крутить дальше!" );												
		}
	}
};

var _curAncets = []; // the information about last updated ancets
var _incOffset = false; // do increment offset when searching?


// show message box if a user made wrong contact settings
var minAllowedDiff = 2;

function _notifyIfWrongProbas( probas )
{
	if( !notifiedWrongProbas )
	{
		var maxDiff = 0;
		for( var i = 1; i < probas.length; i++ )
		{
			var diff = probas[ i ] - probas[ i - 1 ];
			if( diff > maxDiff )
			{
				maxDiff = diff;
			}
		}
			
		if( maxDiff < minAllowedDiff )
		{				


			fancybox( $( '#notify_wrong_probas' ).html() );
			notifiedWrongProbas = true;		

			ajax( 
				{
					'url': "/set-notified-wrong-probas",
					'dataType': "json"
				} 
			);
		}
	}


}


function update()
{
	
	if( !updateMode.isUpdate )
	{
		updateMode.set( true );
		
		if( _notShowedUsers.length >= numPhotosOnScreen )
		{

			var nsuLen = _notShowedUsers.length;

			var photoInfos = [];

			for( var i = 0; i < numPhotosOnScreen; i++ )
			{
				var user = _notShowedUsers[ i ];
	
				var data = user[ 'data' ];
				var info = data[ 'info' ];
				var src = info[ 'medium_photo_url' ];
				var proba = user[ 'proba' ];

				photoInfos.push( { 'src': src, 'proba': proba[ 0 ] } );

				_curAncets[ i ] = user;
			}

			photos.updateAll( photoInfos );
			_notShowedUsers.splice( 0, numPhotosOnScreen );
		}
		else
		{
			var data =	{	
							'inc_offset': _incOffset,	
							'iam': IAM, 
							'look_for': LOOK_FOR,
							'min_age': MIN_AGE,
							'max_age': MAX_AGE,
							'country_id': COUNTRY_ID,
							'region_id': REGION_ID,
							'is_city_id': String( IS_CITY_ID )
						 };
			
			if( IS_CITY_ID )
			{
				data[ 'city_id' ] = CITY_ID;
			}

			ajax(
				{
					'url': "/predict/",
					'data': data,
					'type': "POST",
					'dataType': "json",
					'success':
						function( data )
						{
							var isLimitExceeded = ( data[ 'is_limit_exceeded' ] == "true" ? true : false );							

							if( !isLimitExceeded )
							{							

								var advBlock = data[ 'adv_block' ];

								$( '#adv_div' ).css( 'background-image', "url(" + advBlock[ 'photo_url' ] + ")" );
								$( '#adv_a' ).attr( 'href', advBlock[ 'anketa_link' ] );

								_incOffset = true; // further increment the offset
	
								if( !_isPayedMode )
								{										
									_isPayedMode = true;
									hint.reset();
									$( '#pay' ).fadeOut( 'slow' );
								}
								
								var users = data[ 'users' ];
									
								var lenUsers = users.length;
		
								var updatedPhotos = [];

								var probas = []
	
								for( var i = 0; i < lenUsers; i++ )
								{									
									var user = users[ i ];

		                        	var data = user[ 'data' ];
									var info = data[ 'info' ];
									var src = info[ 'medium_photo_url' ];
									var proba = user[ 'proba' ][ 0 ];
		
									var photoInfo = { 'src': src, 'proba': proba };

									probas.push( parseInt( proba ) );
		
										
									if( i < numPhotosOnScreen )
									{
										updatedPhotos.push( photoInfo );
	                            		
	                            		_curAncets[ i ] = user;
									}
									else
									{
										_notShowedUsers.push( user );
									}
								}

								_notifyIfWrongProbas( probas );

    							photos.updateAll( updatedPhotos );
							}
							else
							{
								// Limit is exceeded

								loader.load(	3, 
												{ 
													is_limit_exceeded: "true", 
													next_section: 4 
												}
								);
							}
						},
					'error':
						function()
						{
							alert( "error!" );
						}
				}
			);	
		}
	}				
}                              

function onHintReset()
{
	if( _isPayedMode )
	{
		hint.reset();
	}
}

function _isHintItem( i, j )
{
	if(	i == 'info' )
	{
		if(	j == 'login' ||
			j == 'name' ||
			j == 'gender' ||
			j == 'anketa_link' ||
			j == 'small_photo_url' ||
			j == 'medium_photo_url' ||
			j == 'square_photo_url' ||
			j == 'age' ||
			j == 'lang' )
		{
			return false;
		}
	}
	else
	if( i == 'familiarity' )
	{
		if(	j == 'children' ||
			j == 'marital' )
		{
			return false;
		}	
	}

	return true;
}

// to set pos after animation if a user clicks to show hint before the end of the animation
var _hintPosAfterUpdate = undefined;

function setHint( pos )
{
	if( _isPayedMode )
	{
		if( updateMode.isUpdate == false )
		{
			var data = _curAncets[ pos ][ 'data' ];		
			var oid = data[ 'info' ][ 'oid' ];

			_messageInfo.name = data[ 'info' ][ 'name' ];
			_messageInfo.photoSrc = data[ 'info' ][ 'small_photo_url' ];
			_messageInfo.ancetUrl = data[ 'info' ][ 'anketa_link' ];
			_messageInfo.oid = data[ 'info' ][ 'oid' ];
			
			if( hint.setPos( pos, oid, updateMode.isUpdate ) )
			{						
				var title = $( '#title_container' ).clone();
	
				title.find( '[name=title]' ).html( data[ 'info' ][ 'name' ] );
				var age = data[ 'info' ][ 'age' ];
				title.find( '[name=age]' ).html( age + " " + getAgeNotation( age ) );

				title.find( '[name=image]' ).attr( 'src', data[ 'info' ][ 'small_photo_url' ] );
	
				var proba = _curAncets[ pos ][ 'proba' ];
				
				title.find( '[name=proba]' ).text( proba );
	
				title.find( '[name=proba_style]' ).attr( 'class', "answer" + String( photos.detectAnswerByProba( proba ) ) );
	
				var content = "<div><div style='margin-bottom: 20px'>{0}</div>{1}</div>";
				var itemContent = "";
				var dataItem = "<div style='border-radius: 3px; background: rgb( 230, 230, 230 ); padding: 2px; float: left; margin-right: 5px; margin-bottom: 10px'>{0}</div>";
	
				for( var i in data )
				{
					var item = data[ i ];
	
					if( typeof item == "string" && item != "" )
					{
						itemContent += format( dataItem, item );
					}
					else
					if( typeof item == "object" )
					{
						for( var j in item )
						{
							var innerItem = item[ j ];
	
							if( _isHintItem( i, j ) && typeof innerItem == "string" && innerItem != "" )
							{
								itemContent += format( dataItem, innerItem );
							}
						}
					}
				}
	
				content = format( content, title.html(), itemContent );
	
				hint.setContent( pos, content );
			}		

			_hintPosAfterUpdate = undefined;
		}
		else
		{
			_hintPosAfterUpdate = pos;
		}
	}
}

var photos =
{
	_lastProbas: [],

	_pushProba: function( proba )
	{
		this._lastProbas.push( proba );

		if( this._lastProbas.length > 20 )
		{
			this._lastProbas.splice( 0, this._lastProbas.length - 20 );
		}
	},

	detectAnswerByProba: function( proba )
	{
		var lenLastProbas = this._lastProbas.length;	

		var max = this._lastProbas[ 0 ];
		var sum = 0;

		for( var i = 0; i < lenLastProbas; i++ )
		{
			var p = this._lastProbas[ i ];
			
			if( max < p )
			{
				max = p;
			}
			else
			{
				max > p
			}

			sum += p;
		}

		var med = sum / lenLastProbas;

		var result;

		if( proba == max )
		{
			result = 2;
		}
		else
		if( proba > med )
		{
			result = 1;
		}
		else
		{
			result = 0;
		}

		return result;
	},

	_update: function( data )
	{				
		var iPhoto = data[ 'iPhoto' ];
		var item = data[ 'item' ];
		var proba = item[ 'proba' ];
		var src = item[ 'src' ];
		
		var root = $( '#photo' + String( iPhoto ) );

		root.find( 'div > div[name=photo] ' ).css( 'background', "url( " + src + ")" );
		
		var imgCaption = root.find( '.img-caption' );

		imgCaption.text( String( proba ) );
	},

	_updateProba: function( data )
	{
		var proba = data[ 'item' ][ 'proba' ];
		var iPhoto = data[ 'iPhoto' ];
		var imgCaption = $( '#photo' + String( iPhoto ) ).find( '.img-caption' );
		imgCaption.attr( 'class', "img-caption answer" + this.detectAnswerByProba( proba ) );
	},

	updateAll: function( data )
	{
		var dataLen = data.length;
		var numPhotos;
		
		if( dataLen >= numPhotosOnScreen )
		{
			numPhotos = numPhotosOnScreen;
		}
		else
		{
			numPhotos = dataLen;
		}

		var nPToShuffle = numPhotosOnScreen;

		var shData = []; // shuffled data
		var numArr = [];

		for( var i = 0; i < numPhotos; i++ )
		{
			numArr.push( i );
		}

		for( i = 0; i < numPhotos; i++ )
		{
			var nShuffle = numPhotos - i;

			var nPh = Math.floor( Math.random() * nShuffle );
			if( nPh > nShuffle - 1 )
			{
				nPh = nShuffle - 1;
			}

			var item = data[ nPh ];

			data.splice( nPh, 1 );
			var iPhoto = numArr[ nPh ];
			numArr.splice( nPh, 1 );

			shData.push( { iPhoto: iPhoto, item: item } );

			this._pushProba( item[ 'proba' ] );
		}

		// update colors for probas
		for( var i = 0; i < numPhotos; i++ )
		{
			this._updateProba( shData[ i ] );
		}

		this._itemLoop( shData );
	},

	_itemLoop: function( data )
	{
		this._update( data[ 0 ] );

		var this_ = this;

		if( data.length > 1 )
		{
			data.splice( 0, 1 );					
			setTimeout( function() { this_._itemLoop( data ); }, 250 );
		}
		else
		{
			updateMode.set( false );
			
			if( this._hintPosAfterUpdate != undefined )
			{
				this.setPosCallback( this._hintPosAfterUpdate );
				this._hintPosAfterUpdate = undefined;
			}
		}
	}
}

var hint =
{
	_html: {},
	_photos: {}, // undefined if photos was not loaded
	_oids: {},

	_loaderHtml: "<img src='/static/img/rect-loader.gif' style='display: block; margin: auto; clear: both'>",

	_showSendImage: function( pos, bShow )
	{
		var display = bShow ? "block": "none";				
		$( '#photo_caption' + String( pos ) ).css( 'display', display );
	},

	_hidePrevSendImage: function()
	{
		if( this._prevPos != undefined )
		{
			this._showSendImage( this._prevPos, false );
		}
	},
	
	setPos: function( pos, oid )
	{
		var result = ( this._html[ pos ] == null );
		
		if( this._pos != pos )		
		{
			var offset = pos * 133 + 36;
	
			this._oids[ pos ] = oid;

			this._curPhotoOid = oid;
			
			this._pos = pos;
			this.show( true );
	
			this._setHintPointerOffset( offset );
	
			if( !result )
			{
				this._setContent( this._html[ pos ] );
			}
			else
			{
				this._setContent( this._loaderHtml );
			}

			// clear photos
			this._getPhotosRoot().empty();
			this._updatePhotos();
	
			this._hidePrevSendImage();
			this._showSendImage( pos, true );
	
			this._prevPos = pos;
	
			return result; // returns true if it is requested content
		}
	},

	_getPhotosRoot: function()
	{
		return $( '[name=small_photos]' );
	},

	_setPhotos: function( html )
	{
		this._getPhotosRoot().html( html );
	},

	_showPhotosLoader: function()
	{
		this._setPhotos( "<img id='ancet-loader' src='/static/img/photos-loader.gif' style='display: block'>" );
	},
	
	_updatePhotos: function()
	{
		// test if we need to load photos

		// if there is no photo for current position
		if( this._photos[ this._pos ] == undefined )
		{		
			// if there are no request for other photos
			if( this._photosUpdated == undefined )
			{
				this._posBeforePhotoReq = this._pos;

		        this._photosUpdated = true; // start photo request
	
				var this_ = this;				

				this._showPhotosLoader();
	
				mamba.api(
					{
						'method': "photos.get",
						'oid': this._oids[ this._posBeforePhotoReq ]
					},
					function( err, data )
					{
	
						var photos = data[ 'data' ][ 'photos' ];
						var root = this_._getPhotosRoot();
						var rootHtml = "";
						
						var photosLen = 0;
						
						if( photos != undefined )
						{
							photosLen = photos.length;

							if( photosLen > MAX_NUM_PHOTOS )
							{
								photosLen = MAX_NUM_PHOTOS;
							}

							var template = "<a id='{4}' class='fancybox-thumb' rel='fancybox-thumb' href='{0}' title='{3}'><img name='small_photo' src='{1}' class='{2}'></a>";
	
							for( var i = 0; i < photosLen - 1; i++ )
							{
								var thumbnailUrl = photos[ i ][ 'square_photo_url' ];
								var photoUrl = photos[ i ][ 'huge_photo_url' ];
								var title = photos[ i ][ 'name' ];
								rootHtml += format(	template,
													photoUrl,
													thumbnailUrl,
													'ancet-small-photo',
													title,
													"fancy" + String( i )
								);
							}
			
							// add last photo
							if( photosLen > 0 )
							{
								var i = photosLen - 1;
								var thumbnailUrl = photos[ i ][ 'square_photo_url' ];	
								var photoUrl = photos[ i ][ 'huge_photo_url' ];
								var title = photos[ i ][ 'name' ];
								rootHtml += format(	template,
													photoUrl,
													thumbnailUrl,
													'ancet-small-photo-last',
													title,
													"fancy" + String( i )
								);
							}
						}
			
						this_._photos[ this_._posBeforePhotoReq ] = rootHtml;

						this_._photosUpdated = undefined;
						
						if( this_._posBeforePhotoReq == this_._pos )
						{
							this_._setPhotos( rootHtml );
							$(".fancybox-thumb").fancybox(
								{
									prevEffect: 'none',
									nextEffect: 'none',
									scrolling: 'yes',
									helpers: 
									{
										title: 
										{
											type: 'inside'
										},
										overlay: 
										{
											locked: false
										}
									}
								}
							);
						}
						else
						{
							setTimeout( function() { this_._updatePhotos() }, 0 );
						}
	
					}
				);
			}
		}
		else
		{
			this._setPhotos( this._photos[ this._pos ] );
		}
	},

	_hintPointerId: "hint-pointer",
	_hintContentId: "hint-content",
	_teaserId: "teaser",

	_setHintPointerOffset: function( offset )
	{
		$( '#' + this._hintPointerId ).css( 'margin-left', String( offset ) + "px" );
	},

	show: function( bShow )
	{
		var prop;
		var invertProp;
		if( bShow )
		{
			prop = "block";
			invertProp = "none";
		}
		else
		{
			prop = "none";
			invertProp = "block";
			this._pos = null;
		}

		$( '#' + this._hintPointerId ).css( 'display', prop );
		$( '#' + this._hintContentId ).css( 'display', prop );
		$( '#' + this._teaserId ).css( 'display', invertProp );		
	},

	_setContent: function( html )
	{
		$( '#hint-content' ).html( html );
	},

	setContent: function( pos, html )
	{			
		this._html[ pos ] = html;

		if( this._pos == pos )
		{
			this._setContent( html );
		}					
	},

	reset: function()
	{
		this._html = {};
		this._photos = {};
		this._oids = {};

		this.show( false );
		this._hidePrevSendImage();
		
		this._pos = undefined;	
	}					
};